<template>
  <div class="supply">
      <el-row :gutter="20">
          <el-col :span="12"> <div class="grid-content bg-purple-dark">
              <el-button @click="dialogFormVisible = true" type="primary" icon="el-icon-plus">添加</el-button>
              <el-dialog title="供应商注册" :visible.sync="dialogFormVisible" width="70%" >
                  <div class="form-scroll-container">
                      <el-progress :percentage="10" :format="format" :show-text="false"></el-progress>
                  <el-form :label-position="labelPosition" label-width="80px" :model="combinedObject" ref="ruleForm" >
                      <el-row :gutter="20">
                      <el-col :span="12" >
                          <el-form-item label="供应商编码">
                              <el-input v-model="combinedObject.supplier.supplierCode"  placeholder="自动生成无需输入" :disabled="true"></el-input>
                          </el-form-item>
                          </el-col>
                          <el-col :span="12" >
                          <el-form-item label="供应商名称" prop="supplier.supplierName" :rules="[
                                { required: true, message: '请输入供应商名称', trigger: ['blur', 'change'] },]">
                              <el-input v-model="combinedObject.supplier.supplierName"></el-input>
                          </el-form-item>
                         </el-col>
                      </el-row>
                      <el-row :gutter="20">
                      <el-col :span="12" >
                              <el-form-item label="供应商分类" prop="supplier.supplierType"
                                            :rules="[
                                { required: true, message: '请选择供应商分类', trigger: ['blur', 'change'] },]">
                                  <template>
                                      <el-select v-model="combinedObject.supplier.supplierType" placeholder="请选择">
                                          <el-option
                                                  v-for="supplierType in supplyTypes"
                                                  :key="'supplierType'+supplierType.dictCode"
                                                  :label="supplierType.dictLabel"
                                                  :value="supplierType.dictLabel"
                                                  >
                                          </el-option>
                                      </el-select>
                                  </template>
                              </el-form-item>
                          </el-col>
                          <el-col :span="12" >
                                  <el-form-item label="供应商状态">
                                      <div style="position: relative;">
                                          <el-input v-model="combinedObject.supplier.supplierState" placeholder="潜在供应商" disabled></el-input>
                                          <el-button disabled type="danger" size="small" style="position: absolute; left: 15px; top: 5px;">潜在供应商</el-button>
                                      </div>
                                  </el-form-item>
                          </el-col>
                          </el-row>
                      <el-row>
                      <el-col :span="24" >
                              <el-form-item label="供应商地址" prop="supplier.cityId" :rules="[
                                { required: true, message: '请选择地址', trigger: ['blur', 'change'] },]" >
                                  <el-cascader
                                          v-model="combinedObject.supplier.cityId"
                                          :options="provinceCityCascade"
                                          @change="handleChange">
                                  </el-cascader>
                                  <el-input v-model="combinedObject.supplier.supplierAddress" placeholder="详细地址"></el-input>
                              </el-form-item>
                          </el-col>
                      </el-row>
                      <el-row>
                              <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                                  <el-tab-pane label="财务信息" name="first">财务信息
                                      <el-progress :percentage="10" :format="format" :show-text="false" ></el-progress>
                                      <el-row :gutter="20">
                                          <el-col :span="12" >
                                              <el-form-item label="发票抬头">
                                                  <el-input v-model="combinedObject.supplier.invoiceHeader"></el-input>
                                              </el-form-item>
                                          </el-col>
                                          <el-col :span="12" >
                                              <el-form-item label="发票税号">
                                                  <el-input v-model="combinedObject.supplier.taxNum"></el-input>
                                              </el-form-item>
                                          </el-col>
                                      </el-row>
                                      <el-row :gutter="20">
                                          <el-col :span="12" >
                                              <el-form-item label="税种" >
                                                  <template>
                                                      <el-select v-model="combinedObject.supplier.taxType" placeholder="请选择">
                                                          <el-option
                                                                  v-for="taxType in taxTypes"
                                                                  :key="'taxType:'+taxType.dictCode"
                                                                  :label="taxType.dictLabel"
                                                                  :value="taxType.dictCode"
                                                          >
                                                          </el-option>
                                                      </el-select>
                                                  </template>
                                              </el-form-item>
                                          </el-col>
                                          <el-col :span="12" >
                                              <el-form-item label="税率">
                                                  <el-input v-model="combinedObject.supplier.taxRate"></el-input>
                                              </el-form-item>
                                          </el-col>
                                          <el-col :span="12" >
                                          <el-form-item label="开户银行">
                                              <template>
                                                  <el-select v-model="combinedObject.supplier.bank" placeholder="请选择">
                                                      <el-option
                                                              v-for="bank in banks"
                                                              :key="'bank:'+bank.dictCode"
                                                              :label="bank.dictLabel"
                                                              :value="bank.dictLabel"
                                                      >
                                                      </el-option>
                                                  </el-select>
                                              </template>
                                          </el-form-item>
                                          </el-col>
                                          <el-col :span="12" >
                                              <el-form-item label="银行账号">
                                                  <el-input v-model="combinedObject.supplier.bankNum"></el-input>
                                              </el-form-item>
                                          </el-col>
                                      </el-row></el-tab-pane>
                                  <el-tab-pane label="联系人信息" name="second">联系人信息
                                      <el-progress :percentage="10" :format="format" :show-text="false" ></el-progress>
                                      <el-row :gutter="20">
                                          <el-col :span="12" >
                                              <el-form-item label="联系人姓名" prop="contactinfo.name" :rules="[
                                { required: true, message: '请输入联系人姓名', trigger: ['blur', 'change'] },]">
                                                  <el-input v-model="combinedObject.contactinfo.name"></el-input>
                                              </el-form-item>
                                          </el-col>
                                          <el-col :span="12" >
                                              <el-form-item label="联系人职位">
                                                  <el-input v-model="combinedObject.contactinfo.job"></el-input>
                                              </el-form-item>
                                          </el-col>
                                          <el-col :span="12" >
                                              <el-form-item label="联系人电话" prop="contactinfo.phone" :rules="[
                                { required: true, message: '请输入联系人姓名', trigger: ['blur', 'change'] },]">
                                                  <el-input v-model="combinedObject.contactinfo.phone"></el-input>
                                              </el-form-item>
                                          </el-col>
                                          <el-col :span="12" >
                                              <el-form-item label="联系人邮箱">
                                                  <el-input v-model="combinedObject.contactinfo.email"></el-input>
                                              </el-form-item>
                                          </el-col>
                                      </el-row></el-tab-pane>
                                  <el-tab-pane label="资质信息" name="third">资质信息
                                      <el-progress :percentage="10" :format="format" :show-text="false"></el-progress>

                                      <el-form>
                                          <el-row :gutter="20">
                                              <el-col :span="12">
                                                  <el-form-item label="资质/证书名称">
                                                      <el-input v-model="combinedObject.attachment.name"></el-input>
                                                  </el-form-item>
                                              </el-col>
                                              <el-col :span="12">
                                                  <el-form-item label="证书类别">
                                                      <el-select v-model="combinedObject.attachment.type" placeholder="请选择">
                                                          <el-option
                                                                  v-for="item in categoryOptions"
                                                                  :key="'item:'+item.dictCode"
                                                                  :label="item.dictLabel"
                                                                  :value="item.dictLabel">
                                                          </el-option>
                                                      </el-select>
                                                  </el-form-item>
                                              </el-col>
                                          </el-row>

                                          <el-row :gutter="20">
                                              <el-col :span="24">
                                                  <el-form-item label="资质/证书附件">
                                                      <el-upload
                                                              class="upload-demo"
                                                              :action="$basePath+'manage/supplier/uploadPic'"
                                                              :on-preview="handlePreview"
                                                              :on-remove="handleRemove"
                                                              :before-remove="beforeRemove"
                                                              :on-success="(res, file) => handleSuccess(res, file, 'attachment')"
                                                              :headers="headers"
                                                              :on-exceed="handleExceed"
                                                             >
                                                          <el-button size="small" type="primary">点击上传</el-button>
                                                      </el-upload>
                                                  </el-form-item>
                                              </el-col>
                                          </el-row>
                                      </el-form>
                                  </el-tab-pane>
                              </el-tabs>
                      </el-row>
                  </el-form>
                  </div>
                  <div slot="footer" class="dialog-footer">
                      <el-button @click="dialogFormVisible = false">取 消</el-button>
                      <el-button type="primary" @click="submitMyForm('combinedObject')">确 定</el-button>
                  </div>
              </el-dialog>
          </div></el-col>
          <el-col :span="12">
              <el-form :inline="true" :model="supplier" class="demo-form-inline">
              <el-form-item label="供应商名称">
                  <el-input v-model="supplier.supplierName" placeholder="供应商名称" clearable></el-input>
              </el-form-item>
              <el-form-item>
                  <el-button type="primary" @click="getSuppliers(1)">查询</el-button>
              </el-form-item>
          </el-form></el-col>
      </el-row>
    <el-table
            :data="supplierPageInfo.list"
            height="950px"
            max-height="100%"
            border
            style="width: 100%">
        <el-table-column
                type="index"
                width="180" label="序号">
        </el-table-column>
        <el-table-column
                prop="supplierName"
                label="供应商名称"
                width="180">
        </el-table-column>
        <el-table-column
                prop="supplierState"
                label="供应商状态"
                width="180"
        >
            <template slot-scope="scope">
                <el-button v-if="scope.row.supplierState === '合格供应商'" type="success">{{ scope.row.supplierState }}</el-button>
                <el-button v-else-if="scope.row.supplierState === '潜在供应商'" type="danger">{{ scope.row.supplierState }}</el-button>
                <el-button v-if="scope.row.supplierState === '一级供应商'" type="success">{{ scope.row.supplierState }}</el-button>
                <el-button v-else-if="scope.row.supplierState === '二级供应商'" type="danger">{{ scope.row.supplierState }}</el-button>
                <el-button v-if="scope.row.supplierState === '三级供应商'" type="success">{{ scope.row.supplierState }}</el-button>
            </template>

        </el-table-column>
        <el-table-column
                prop="supplierType"
                label="供应商分类"
                width="180">
            <template slot-scope="scope">
                <el-button v-if="scope.row.supplierType === '零件供应商'" type="warning">{{ scope.row.supplierType }}</el-button>
                <el-button v-else-if="scope.row.supplierType === '集合供应商'" type="success">{{ scope.row.supplierType }}</el-button>
                <el-button v-else-if="scope.row.supplierType === '成品供应商'" type="danger">{{ scope.row.supplierType }}</el-button>
            </template>
        </el-table-column>
        <el-table-column
                prop="supplierCode"
                label="供应商编码">
        </el-table-column>

        <el-table-column
                prop="supplierAddress"
                label="供应商地址"
                width="180">
        </el-table-column>
        <el-table-column
                prop="supplierSign.startTime"
                label="签约开始日期"
                width="180">
        </el-table-column>
        <el-table-column
                prop="supplierSign.endTime"
                label="签约结束日期">
        </el-table-column>
        <el-table-column
                prop="supplierSign.supplierSignDeadline"
                label="结算期限"
                width="180">
        </el-table-column>

        <el-table-column
                prop="supplierSign.creditLimit"
                label="信用额度"
                width="180">
        </el-table-column>
        <el-table-column
                prop="attachment.name"
                label="资质/证书名称">
        </el-table-column>

        <el-table-column
                prop="attachment.type"
                label="证书类型"
                width="180">
        </el-table-column>
        <el-table-column
                prop="attachment.upFileName"
                label="资质/证书附件"
                width="180">
            <template slot-scope="scope">
                <img :src="$basePath+'static/uploadImages/'+scope.row.attachment.upFileName" style="max-width: 100px">
            </template>
        </el-table-column>
        <el-table-column
                prop="contactinfo.name"
                label="联系人姓名">
        </el-table-column>
        <el-table-column
                prop="contactinfo.phone"
                label="联系人电话"
                width="180">
        </el-table-column>

        <el-table-column
                prop="contactinfo.job"
                label="联系人职位"
                width="180">
        </el-table-column>

        <el-table-column
                prop="invoiceHeader"
                label="发票抬头"
                width="180">
        </el-table-column>
        <el-table-column
                prop="taxNum"
                label="税号"
                width="180">
        </el-table-column>
        <el-table-column
                prop="taxType"
                label="税种"
                width="180">
        </el-table-column>
        <el-table-column
                prop="taxRate"
                label="税率"
                width="180">
        </el-table-column>
        <el-table-column
                prop="bank"
                label="开户银行"
                width="180">
        </el-table-column>
        <el-table-column
                prop="bankNum"
                label="银行账号"
                width="180">
        </el-table-column>
        <el-table-column
                prop="invoiceHeader"
                label="发票抬头"
                width="180">
        </el-table-column>
        <el-table-column
                prop="updateTime"
                label="更新时间"
                width="180">
            <template slot-scope="scope">
                <span>{{$dayjs(scope.row.updateTime).format('YYYY-MM-DD')}}</span>
            </template>
        </el-table-column>
    </el-table>
      <template>
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
      >
      </el-pagination>
      </template>
  </div>
</template>

<script>
    export default {
        name: "SupplierListView",
        data() {
            return {
                currentPage:1,
                total:0,
                pageSize:5,
                combinedObject: {
                    supplier:{
                        supplierCode:'',
                        supplierNum:'',
                        supplierName:'',
                        supplierType: '',
                        supplierState:'潜在供应商',
                        supplierAddress:'',
                        invoiceHeader:'',
                        taxNum:'',
                        taxType:'',
                        taxRate:'',
                        bank:'',
                        bankNum:'',
                        cityId:''
                    },
                    //联系人
                    contactinfo:{
                        name:'',
                        job:'',
                        phone:'',
                        email:'',
                        supplierId:'',
                    },
                    //附件表 //资质
                    attachment: {
                        name: '',
                        supplierId:'',
                        type: '',
                        upFileName:{ name: '', url: '' }
                    },
                },
                supplier: {},
                submitData:{},
                suppliers: [],
                beginTime:'',
                endTime:'',
                supplyTypes:[],
                // 用于存储用户选择的供应类型
                selectedSupplyType: '',
                dialogTableVisible: false,
                dialogFormVisible: false,
                labelPosition: 'top',
                formLabelAlign: {
                    name: '',
                    region: '',
                    type: ''
                },
                provinceCityCascade: [],
                selectedOptions: [],
                taxTypes:[],
                banks:[],
                //证书类别
                categoryOptions: [],
                activeName: 'first',
                headers:{token:window.localStorage.getItem("token")},
                supplierPageInfo:{},
            }

        },
       created() {
            this.getSuppliers(1);
            this.getProvinceCityCascade();
            this.fetchAllData();
       },
        methods:{
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                this.currentPage = 1;
                this.getSuppliers();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.getSuppliers(val);
                this.currentPage = val;
            },
            getSuppliers(pageNum){
                console.log(this.supplier);
            this.$axios.post("manage/supplier/list",this.supplier,{params:{pageNum:pageNum,pageSize:this.pageSize}}).then(
                response=>{
                    if (response.data) {
                        const data = response.data;
                        console.log(response.data);
                        this.supplierPageInfo = data.supplierPageInfo; // 更新分页信息
                        this.total = data.supplierPageInfo.total; // 更新总数据量

                        this.suppliers = data.supplierPageInfo.list; // 更新供应商列表
                    } else {
                        console.error("请求失败:", response.data.message);
                    }
                }).catch(error => {
                console.error("请求错误:", error);
            });
        },
            async getSupplyTypes() {
                try {
                    const response = await this.$axios.get("manage/scmDictData/dictDataList", {
                        params: { dataType: 'supplier_type' }
                    });
                    this.supplyTypes = response.data.dataType || [];
                    //console.log('供应类型:', this.supplyTypes);
                } catch (error) {
                    // console.error("获取供应类型数据失败：", error);
                    //alert("获取供应类型失败,请刷新重试");
                }
            },
            async getTaxTypes() {
                try {
                    const response = await this.$axios.get("manage/scmDictData/dictDataList", {
                        params: { dataType: 'tax_type' }
                    });
                    this.taxTypes = response.data.dataType || [];
                    //console.log('税率类型:', this.taxTypes);
                } catch (error) {
                    console.error("获取税率数据失败：", error);
                   //  alert("获取税率失败,请刷新重试");
                }
            },
            async getBanks() {
                try {
                    const response = await this.$axios.get("manage/scmDictData/dictDataList", {
                        params: { dataType: 'bank' }
                    });
                    this.banks = response.data.dataType || [];
                    //console.log('银行列表:', this.banks);
                } catch (error) {
                   // console.error("获取银行数据失败：", error);
                    alert("获取银行失败,请刷新重试");
                }
            },
            async getCertificateType(){
                try {
                    const response = await this.$axios.get("manage/scmDictData/dictDataList", {
                        params: { dataType: 'certificate_type' }
                    });
                    this.categoryOptions = response.data.dataType || [];

                } catch (error) {
                    alert("获取证书失败,请刷新重试");
                }
            },
            async fetchAllData() {
                await Promise.all([this.getSupplyTypes(), this.getTaxTypes(), this.getBanks(),  this.getCertificateType()]);
            },
            getProvinceCityCascade(){
                this.$axios.get("manage/city/provinceCityCascade").then(
                    response=>{
                        this.provinceCityCascade = response.data.provinceCityCascade;
                    });
            },
            handleRemove(file, upFileName) {
                // console.log(file, upFileName);
            },
            handlePreview(file) {
                // console.log(file);
            },
            handleExceed(files, upFileName) {
                this.$message.warning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + upFileName.length} 个文件`);
            },
            beforeRemove(file, upFileName) {
                return this.$confirm(`确定移除 ${ file.name }？`);
            },
            handleSuccess(res, file) {
                // console.log(res,file);
                this.combinedObject.attachment.upFileName.url = this.$basePath+"static/uploadImages/"+res.fileName;
                this.combinedObject.attachment.upFileName=res.fileName;

            },
            format(percentage) {
                return percentage === 100 ? '满' : `${percentage}%`;
            },
            handleClick(tab, event) {
                // console.log(tab, event);
            },
            handleChange(value) {
                // console.log(value);
                if (value.length > 0) {
                    // 假设最后一级是城市，因此取最后一个元素作为 cityId
                    this.combinedObject.supplier.cityId = value[value.length - 1];
                } else {
                    this.combinedObject.supplier.cityId = null;
                }

            },
            submitMyForm(formName) {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        this.$axios.post("manage/supplier/add", this.combinedObject)
                            .then(response => {
                                // 成功处理逻辑
                                this.$message({
                                    message: '供应商信息录入成功,请前往审核',
                                    type: 'success',
                                });
                                // 关闭对话框并清空内容
                                this.dialogFormVisible = false;
                            })
                            .catch(error => {
                                // 错误处理逻辑
                                console.error("提交失败:", error);
                                this.$message.error('提交失败，请重试');
                            });
                    } else {
                        console.log('验证失败!');
                        return false;
                    }
                });
            },
        }
    }
</script>

<style scoped>
    .el-row{
       padding-left: 3px;
        padding-bottom: 3px;
    }
    .supply{
        height: 740px;

    }
    .form-scroll-container {
        max-height: 400px; /* 根据需要调整高度 */
        overflow-y: auto;
        padding: 10px; /* 可选，根据需要添加内边距 */
        border: 1px solid #dcdfe6; /* 可选，根据需要添加边框 */
        border-radius: 4px; /* 可选，根据需要添加圆角 */
    }
    .el-input{
        width: 350px;
    }

</style>